﻿Option Strict Off
Imports System.Net.Mail
Imports System.Drawing
Imports System.Net.Mime

Namespace My

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication

        Dim myMailMessage As New MailMessage("BoEllisAnderson@aol.com", "BoEllisAnderson@aol.com")

        Private Sub MyApplication_NetworkAvailabilityChanged(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs) Handles Me.NetworkAvailabilityChanged
            If e.IsNetworkAvailable = False Then
                Dim msgbox1 As MsgBoxResult = MsgBox("The connection to the internet appears to have been disconnected. Please reconnect and try again.", MsgBoxStyle.Exclamation, "Error")
            End If
        End Sub

        Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
            e.ExitApplication = False

            Dim status As String = ""

            Try
                myMailMessage.Body = Nothing
                myMailMessage.Priority = MailPriority.High
                myMailMessage.Subject = "BBrowser Unhandled Exception"

                Dim mediatype As String = "text/html"
                Dim bodytext As String = Me.CreateExceptionText(e.Exception)
                Dim HTMLContent As AlternateView = AlternateView.CreateAlternateViewFromString(bodytext, Nothing, mediatype)

                myMailMessage.Body = bodytext

                If My.Settings.IsFormOpen = True Then
                    Me.TakeScreenShot()
                ElseIf My.Settings.IsFormOpenTabs = True Then
                    Me.TakeScreenShotTabs()
                End If

                myMailMessage.Attachments.Clear()

                'Dim screenshot As New LinkedResource("error.jpg")
                Dim screenshot As New Attachment("error.jpg", MediaTypeNames.Image.Jpeg)
                'screenshot.ContentId = "SCREENSHOT"

                myMailMessage.Body = Nothing
                status = "addhtmlcontent"
                'HTMLContent.LinkedResources.Add(screenshot)
                myMailMessage.Attachments.Add(screenshot)
                myMailMessage.AlternateViews.Add(HTMLContent)
            Catch ex As Exception
                If myMailMessage.Body = Nothing And status = "" Then
                    MsgBox("An unexpected exception has occurred. The email including the exception log could not be sent to tech support.", MsgBoxStyle.Critical, "Error")
                    If My.Settings.CloseAfterUnhandledException = True Then
                        e.ExitApplication = True
                    ElseIf My.Settings.CloseAfterUnhandledException = False Then
                        e.ExitApplication = False
                    End If
                    Exit Sub
                ElseIf Not myMailMessage.Body = Nothing Then

                    myMailMessage.Subject = "BBrowser Unhandled Exception (Basic log - Error occured in ApplicationEvents.vb while taking screenshot)"

                    Dim smtpServer1 As New SmtpClient("smtp.aol.com")

                    smtpServer1.EnableSsl = True
                    smtpServer1.Credentials = New System.Net.NetworkCredential("BoEllisAnderson", "RED123")
                    smtpServer1.Port = 587
                    Try
                        smtpServer1.Send(myMailMessage)
                    Catch ex1 As Exception
                        SendEmailAttempt2()
                    End Try

                    Try
                        My.Computer.FileSystem.DeleteFile("C:\error.jpg")
                        myMailMessage.Attachments.Clear()
                        myMailMessage.Dispose()
                    Catch ex1 As Exception

                    End Try

                    MsgBox("An unexpected exception has occurred. The exception log has been sent to tech support so they can fix it for future releases.", MsgBoxStyle.Critical, "Error")
                    If My.Settings.CloseAfterUnhandledException = True Then
                        e.ExitApplication = True
                    ElseIf My.Settings.CloseAfterUnhandledException = False Then
                        e.ExitApplication = False
                    End If
                    Exit Sub

                ElseIf myMailMessage.Body = Nothing And status = "addhtmlcontent" Then
                    Dim bodytext1 As String = Me.CreateExceptionText(e.Exception)
                    myMailMessage.Body = bodytext1

                    myMailMessage.Subject = "BBrowser Unhandled Exception (Basic log - Error occured in ApplicationEvents.vb while adding HTML)"

                    Dim smtpServer2 As New SmtpClient("smtp.aol.com")

                    smtpServer2.EnableSsl = True
                    smtpServer2.Credentials = New System.Net.NetworkCredential("BoEllisAnderson", "RED123")
                    smtpServer2.Port = 587
                    Try
                        smtpServer2.Send(myMailMessage)
                    Catch ex1 As Exception
                        SendEmailAttempt2()
                    End Try

                    Try
                        My.Computer.FileSystem.DeleteFile("C:\error.jpg")
                        myMailMessage.Attachments.Clear()
                        myMailMessage.Dispose()
                    Catch ex1 As Exception

                    End Try

                    MsgBox("An unexpected exception has occurred. The exception log has been sent to tech support so they can fix it for future releases.", MsgBoxStyle.Critical, "Error")
                    If My.Settings.CloseAfterUnhandledException = True Then
                        e.ExitApplication = True
                    ElseIf My.Settings.CloseAfterUnhandledException = False Then
                        e.ExitApplication = False
                    End If
                    Exit Sub

                Else
                    Try
                        My.Computer.FileSystem.DeleteFile("C:\error.jpg")
                        myMailMessage.Attachments.Clear()
                        myMailMessage.Dispose()
                    Catch ex1 As Exception

                    End Try

                    MsgBox("An unexpected exception has occurred. The email including the exception log could not be sent to tech support.", MsgBoxStyle.Critical, "Error")
                    If My.Settings.CloseAfterUnhandledException = True Then
                        e.ExitApplication = True
                    ElseIf My.Settings.CloseAfterUnhandledException = False Then
                        e.ExitApplication = False
                    End If
                    Exit Sub
                End If
            End Try

            Dim smtpServer As New SmtpClient("smtp.aol.com")

            smtpServer.EnableSsl = True
            smtpServer.Credentials = New System.Net.NetworkCredential("BoEllisAnderson", "RED123")
            smtpServer.Port = 587

            Try
                smtpServer.Send(myMailMessage)
            Catch ex As Exception
                SendEmailAttempt2()
                If My.Settings.CloseAfterUnhandledException = True Then
                    e.ExitApplication = True
                ElseIf My.Settings.CloseAfterUnhandledException = False Then
                    e.ExitApplication = False
                End If
                Exit Sub
            End Try

            Try
                My.Computer.FileSystem.DeleteFile("C:\error.jpg")
                myMailMessage.Attachments.Clear()
                myMailMessage.Dispose()
            Catch ex As Exception

            End Try

            MsgBox("An unexpected exception has occurred. The exception log has been sent to tech support so they can fix it for future releases.", MsgBoxStyle.Critical, "Error")

            If My.Settings.CloseAfterUnhandledException = True Then
                e.ExitApplication = True
            ElseIf My.Settings.CloseAfterUnhandledException = False Then
                e.ExitApplication = False
            End If
        End Sub

        Private Sub TakeScreenShot()
            Dim bounds As Rectangle = BrowserWithoutTabs1.Bounds

            Using b As New Bitmap(bounds.Width, bounds.Height)
                Try
                    My.Computer.FileSystem.DeleteFile("C:\error.jpg")
                Catch ex As Exception

                End Try

                Dim g As Graphics = Graphics.FromImage(b)
                g.CopyFromScreen(BrowserWithoutTabs1.Location, Point.Empty, bounds.Size)

                b.Save("C:\error.jpg", Imaging.ImageFormat.Jpeg)
            End Using

        End Sub

        Private Sub TakeScreenShotTabs()
            Dim bounds As Rectangle = BrowserWithoutTabs.Bounds

            Using b As New Bitmap(bounds.Width, bounds.Height)
                Try
                    My.Computer.FileSystem.DeleteFile("C:\error.jpg")
                Catch ex As Exception

                End Try

                Dim g As Graphics = Graphics.FromImage(b)
                g.CopyFromScreen(BrowserWithoutTabs.Location, Point.Empty, bounds.Size)

                b.Save("C:\error.jpg", Imaging.ImageFormat.Jpeg)
            End Using

        End Sub

        Private Function CreateExceptionText(ByVal ex As Exception) As String
            Return <p>
                       <pre>
------------------------------------------------------
An unhandled exception occurred in Simplicity Browser
------------------------------------------------------
<%= FormatException(ex) %>
                       </pre>
                   </p>.ToString
        End Function

        Private Function FormatException(ByVal ex As Exception) As String
            If ex Is Nothing Then
                Return ""
            Else
                Return <pre><%= ex.ToString %>
---------------------------------------------
<%= FormatException(ex.InnerException) %>
                       </pre>.Value
            End If
        End Function

        Private Sub SendEmailAttempt2()
            Dim smtpServer As New SmtpClient("smtp.aol.com")

            smtpServer.EnableSsl = True
            smtpServer.Credentials = New System.Net.NetworkCredential("BoEllisAnderson", "RED123")
            smtpServer.Port = 587
            Try
                smtpServer.Send(myMailMessage)
            Catch ex As Exception
                SendEmailAttempt3()
                Exit Sub
            End Try

            MsgBox("An unexpected exception has occurred. The exception log has been sent to tech support so they can fix it for future releases.", MsgBoxStyle.Critical, "Error")
        End Sub

        Private Sub SendEmailAttempt3()
            Dim smtpServer As New SmtpClient("smtp.aol.com")

            smtpServer.EnableSsl = True
            smtpServer.Credentials = New System.Net.NetworkCredential("BoEllisAnderson", "RED123")
            smtpServer.Port = 587
            Try
                smtpServer.Send(myMailMessage)
            Catch ex As Exception
                MsgBox("An unexpected exception has occurred. The email including the exception log could not be sent to tech support.", MsgBoxStyle.Critical, "Error")
                Exit Sub
            End Try

            MsgBox("An unexpected exception has occurred. The exception log has been sent to tech support so they can fix it for future releases.", MsgBoxStyle.Critical, "Error")
        End Sub
    End Class

End Namespace

